package com.meizhuang.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.meizhuang.controller.RSAEncrypt;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.ScheduledUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.*;

import com.meizhuang.entity.enums.SystemParameterEnum;
import com.meizhuang.interceptor.SessionInterceptor;
import com.meizhuang.interceptor.SystemInterceptor;
import com.meizhuang.interceptor.TokenInterceptor;
import com.meizhuang.utils.SystemParameterUtils;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


	public static final String USE_SYSTEM = "meizhuang-api";

	private static Set<String> ignore = new HashSet<String>();

	static {
		ignore.add("/swagger-resources"); // API文档接口
		ignore.add("/swagger-ui.html"); // API文档接口
	}

	@Autowired
	TokenInterceptor tokenInterceptor;
	@Autowired
	SystemInterceptor systemInterceptor;
	@Autowired
	SessionInterceptor sessionInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
//		registry.addInterceptor(tokenInterceptor).addPathPatterns("/**") //
//				.excludePathPatterns(ignore.toArray(new String[ignore.size()]));
//
//		registry.addInterceptor(systemInterceptor).addPathPatterns("/**") //
//				.excludePathPatterns(ignore.toArray(new String[ignore.size()]));
		
		registry.addInterceptor(sessionInterceptor).addPathPatterns("/**") 
		.excludePathPatterns(ignore.toArray(new String[ignore.size()]));
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		registry.addResourceHandler("/File/**").addResourceLocations("file:File/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");

		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");

		String path =  SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);
        registry.addResourceHandler("/getFile/**").addResourceLocations("file:"+path+"/");
	}

	@Bean
	public InternalResourceViewResolver setupViewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;

	}

	/**
	 * 获取签名验证器
	 * 签名验证器: 用于验签的对象
	 */
	@Bean
	public ScheduledUpdateCertificatesVerifier getVerifier() throws IOException {

		String apiV3Key = "yuanbaojia123456yuanbaojia123456";
		String mchid = "1601615594";
		String serialNumber = "40E50643A15A2AA244D392E93033C3EB1844406A";
		String fileName = "apiclient_key.pem";

		//获取商户私钥
		PrivateKey privateKey = RSAEncrypt.getPrivateKey(fileName);

		//私钥签名对象
		PrivateKeySigner privateKeySigner = new PrivateKeySigner(serialNumber, privateKey);

		//身份认证对象
		WechatPay2Credentials wechatPay2Credentials = new WechatPay2Credentials(mchid, privateKeySigner);

		// 使用定时更新的签名验证器，不需要传入证书
		ScheduledUpdateCertificatesVerifier verifier = new ScheduledUpdateCertificatesVerifier(
				wechatPay2Credentials,
				// 异常定位到这里, 说 apiV3Key 的长度有问题
				apiV3Key.getBytes(StandardCharsets.UTF_8));

		return verifier;
	}
	@Override
	public void addCorsMappings(CorsRegistry registry){
		registry.addMapping("/*/**")
				.allowedHeaders("*")
				.allowedMethods("*")
				.maxAge(1800)
				.allowedOrigins("*");
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		converters.add(mappingJackson2HttpMessageConverter());
	}
	// 解决序列化空对象问题
	private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
		ObjectMapper mapper = new ObjectMapper();
		// 关键代码
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		MappingJackson2HttpMessageConverter converter =
				new MappingJackson2HttpMessageConverter(mapper);
		return converter;
	}
}
